<template>
<!--  <doc-alert title="会员用户、标签、分组" url="https://doc.iocoder.cn/member/user/" />-->

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="身份证号" prop="idcard">
        <el-input
          v-model="queryParams.idcard"
          class="!w-240px"
          clearable
          placeholder="请输入身份证号码"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          class="!w-240px"
          clearable
          placeholder="请输入手机号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户标签" prop="tagIds">
        <MemberTagSelect v-model="queryParams.tagIds" />
      </el-form-item>
      <el-form-item label="用户分组" prop="groupId">
        <MemberGroupSelect v-model="queryParams.groupId" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button type="danger">添加到案件</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="头像" prop="avatar" width="60px">
        <template #default="scope">
          <img :src="scope.row.avatar" style="width: 40px"  alt=""/>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idcard" width="180px"/>
      <el-table-column align="center" label="姓名" prop="name" width="100px" />
      <el-table-column align="center" label="手机号" prop="mobile" width="120px" />
      <el-table-column align="center" label="分类" prop="groupName" width="100px" />
      <el-table-column align="center" label="管控单位" prop="deptName" width="150px" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180px"
      />
      <el-table-column
        :show-overflow-tooltip="false"
        align="center"
        fixed="right"
        label="操作"
        width="100px"
      >
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button link type="primary" @click="openDetail(scope.row.id)">详情</el-button>
            <el-dropdown
              v-hasPermi="[
                'member:user:update',
              ]"
              @command="(command) => handleCommand(command, scope.row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="checkPermi(['member:user:update'])"
                    command="handleUpdate"
                  >
                    编辑人员
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="checkPermi(['member:user:delete'])"
                    command="handleDelete"
                  >
                    删除人员
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 导入人员 -->
  <MemberImportForm ref="importMemberFormRef" @success="getList" />

  <UserFormDialog
    ref="idcardFormRef"
    user-type="idcard"
    :foreigner="2"
    @success="getList"
  />

</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import UserForm from './UserForm.vue'
import UserFormDialog from './UserFormDialog.vue'
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import MemberImportForm from './components/MemberImportForm.vue';
import { checkPermi } from '@/utils/permission'
import {t} from "@wangeditor/editor";

defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  groupId: null,
  levelId: null,
  idcard: undefined,
  name: undefined,
  sex: undefined,
  country: undefined,
  nation: undefined,
  avatar: undefined,
  remark: undefined,
  phoneNumber: undefined,
  carNumber: undefined,
  passportNumber: undefined,
  faith: undefined,
  enFirstName: undefined,
  enSecondName: undefined,
  liveAddress: undefined,
  birthPlace: undefined,
  foreigner: 2
})
const queryFormRef = ref() // 搜索的表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

// 国内用户表单 (foreigner = 2)
// const idcardFormRef = ref()
// const openIdcardForm = (type, id) => {
//   idcardFormRef.value.open(type, id)
// }

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导入操作 */
const importMemberFormRef = ref()
const openImportForm = () => {
  importMemberFormRef.value.open()
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 删除按钮操作 */
const handleDelete = async (row: UserApi.UserVO) => {
  try {
    // 检查 ID 是否有效
    if (row.id === undefined || row.id === null) {
      message.error('用户ID无效')
      return
    }

    // 删除确认
    await message.delConfirm(`确定删除人员【${row.nickname}】吗？`, "删除提示")
    await UserApi.deleteUser(row.id) // 确保这里传递的是 number
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    message.error('删除失败')
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      // openIdcardForm('update', row.id)
      openForm('update', row.id)
      break
    case 'handleDelete':
      handleDelete(row)
      break
    default:
      break
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
